<template>
  <div class="app-container">
    <div class="searchStyle">
      <div class="searchStyle">
        <div>
          <el-input
            v-model="queryParams.deptName"
            placeholder="排班组织查询"
            :prefix-icon="Search"
            style="width: 200px;margin-right: 15px;"
            @keyup.enter="handleQuery"
          />
        </div>
        <div>
          <el-select
            v-model="queryParams.type"
            style="width: 200px;margin-right: 15px;"
            placeholder="全部类型"
            @change="handleQuery"
            clearable
          >
            <el-option
              v-for="item in [{value: 0,  name: '一班'}, {value: 1,  name: '二班'}, {value: 2,  name: '三班'}]"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </div>
      </div>
      <div>
        <el-button
          type="primary"
          plain
          @click="handleAdd"
          v-hasPermi="['system:setting:add']"
          >新建</el-button
        >
        <!-- <el-button
          type="warning"
          plain
          @click="handleExport"
          v-hasPermi="['system:setting:export']"
          >导入</el-button
        > -->
      </div>
    </div>

    <el-table v-loading="loading" :data="settingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="排班组织" align="center" prop="deptName" />
      <el-table-column label="排班责任人" align="center" prop="responsibleByName" />
      <el-table-column label="排版类型" align="center" prop="type">
        <template #default="scope">
          <span v-if="scope.row.type == 0">一班</span>
          <span v-else-if="scope.row.type == 1">二班</span>
          <span v-else>三班</span>
        </template>
      </el-table-column>
      <el-table-column label="是否午休" align="center" prop="isNoonBreak">
        <template #default="scope">
          <span v-if="scope.row.isNoonBreak == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-if="userInfo.deptAdmin"
            >编辑</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-else
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 编辑【请填写功能名称】对话框 -->
    <el-dialog title="编辑排班" v-model="editDialog.open" width="1200px" append-to-body class="rosteringEditDialog">
      <h5 class="h5 h51">排班基础信息</h5>
      <el-form ref="editDialogFormRef" :model="editDialog.form" :rules="editDialog.rules" label-width="110px" label-position="top" :disabled="!userInfo.deptAdmin">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排班组织" prop="deptId">
              <el-cascader
              style="width: 100%;"
              v-model="editDialog.form.deptId"
              placeholder="选择组织"
              separator="-"
              :props="{ label: 'deptName', value: 'deptId'}"
              :options="deptOptions" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排班责任人" prop="responsibleBy">
              <el-tree-select
                v-model="editDialog.form.responsibleBy"
                :data="userOptions"
                :render-after-expand="false"
                show-checkbox
                :props="{
                value: 'id',
                label: 'label',
                children: 'children',
                // 可选：禁用用户节点选择
                disabled: (data) => !data.isUser
                }"
                check-strictly
                check-on-click-node
                node-key='id'
                filterable
                style="width: 100%"
                placeholder="选择排班责任人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排班类型" prop="type">
              <el-select v-model="editDialog.form.type">
                <el-option label="一班" :value="0" />
                <el-option label="二班" :value="1" />
                <el-option label="三班" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否午休" prop="isNoonBreak">
              <el-radio-group v-model="editDialog.form.isNoonBreak">
                <el-radio :value="1">午休</el-radio>
                <el-radio :value="0">无午休</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <h5 class="h5">排班日历</h5>
      <ShiftCalendar ref="shiftCalendarRef" :form="editDialog.form" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editCancel">取 消</el-button>
          <el-button type="primary" @click="editSubmitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

     <!-- 新增【请填写功能名称】对话框 -->
     <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="settingRef" :model="form" :rules="rules" label-width="110px" label-position="top">
        <el-form-item label="排班组织" prop="deptId">
          <el-cascader
          style="width: 100%;"
          v-model="form.deptId"
          placeholder="选择组织"
          separator="-"
          :props="{ label: 'deptName', value: 'deptId'}"
          :options="deptOptions" />
        </el-form-item>

        <el-form-item label="排班责任人" prop="responsibleBy">
          <el-tree-select
            v-model="form.responsibleBy"
            :data="userOptions"
            :render-after-expand="false"
            show-checkbox
            :props="{
            value: 'id',
            label: 'label',
            children: 'children',
            // 可选：禁用用户节点选择
            disabled: (data) => !data.isUser
            }"
            check-strictly
            check-on-click-node
            node-key='id'
            filterable
            style="width: 100%"
            placeholder="选择排班责任人"
          />
        </el-form-item>

        <el-form-item label="排班类型" prop="type">
          <el-select v-model="form.type">
            <el-option label="一班" value="0" />
            <el-option label="二班" value="1" />
            <el-option label="三班" value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="是否午休" prop="isNoonBreak">
          <el-radio-group v-model="form.isNoonBreak">
            <el-radio value="1">午休</el-radio>
            <el-radio value="0">无午休</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="早班人员" prop="firstTeam">
          <el-tree-select
            v-model="form.firstTeam"
            :data="userOptions"
            :render-after-expand="false"
            show-checkbox
            :props="{
            value: 'id',
            label: 'label',
            children: 'children',
            // 可选：禁用用户节点选择
            disabled: (data) => !data.isUser
            }"
            check-strictly
            check-on-click-node
            node-key='id'
            filterable
            multiple
            style="width: 100%"
            placeholder="选择排班责任人"
          />
        </el-form-item>
        <el-form-item label="早班时间范围" prop="firstTime">
          <el-time-picker
            v-model="form.firstTime"
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="HH:mm"
            value-format="HH:mm"
            :picker-options="{
              selectableRange: '00:00:00 - 23:59:59'
            }"
          />
        </el-form-item>
        <el-form-item label="中班人员">
          <el-tree-select
            v-model="form.secondTeam"
            :data="userOptions"
            :render-after-expand="false"
            show-checkbox
            :props="{
            value: 'id',
            label: 'label',
            children: 'children',
            // 可选：禁用用户节点选择
            disabled: (data) => !data.isUser
            }"
            check-strictly
            check-on-click-node
            node-key='id'
            filterable
            multiple
            style="width: 100%"
            placeholder="选择排班责任人"
          />
        </el-form-item>
        <el-form-item label="中班时间范围">
          <el-time-picker
            v-model="form.secondTime"
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="HH:mm"
            value-format="HH:mm"
            :picker-options="{
              selectableRange: '00:00:00 - 23:59:59'
            }"
          />
        </el-form-item>

        <el-form-item label="晚班人员">
          <el-tree-select
            v-model="form.thirdTeam"
            :data="userOptions"
            :render-after-expand="false"
            show-checkbox
            :props="{
            value: 'id',
            label: 'label',
            children: 'children',
            // 可选：禁用用户节点选择
            disabled: (data) => !data.isUser
            }"
            check-strictly
            check-on-click-node
            node-key='id'
            filterable
            multiple
            style="width: 100%"
            placeholder="选择排班责任人"
          />
        </el-form-item>
        <el-form-item label="晚班时间范围">
          <el-time-picker
            v-model="form.thirdTime"
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="HH:mm"
            value-format="HH:mm"
            :picker-options="{
              selectableRange: '00:00:00 - 23:59:59'
            }"
          />
        </el-form-item>

        <el-form-item label="适用日期范围" prop="applyDate">
          <el-date-picker
            v-model="form.applyDate"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="rostering">
import { Calendar, Search, Share } from "@element-plus/icons-vue"
import {
  scheduleList,
  addSchedule,
  putSchedule,
} from "@/api/system/setting"
import ShiftCalendar from '@/components/ShiftCalendar/index.vue'
import useUserStore from "@/store/modules/user"
import { deptSonUserTree } from "@/api/system/role"

const { proxy } = getCurrentInstance()

const settingList = ref([])
const open = ref(false)
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const shiftCalendarRef = ref(null)
const userInfo = ref({})

const data = reactive({
  form: {
    deptId: null,
    responsibleBy: null,
    type: null,
    isNoonBreak: '0',
    firstTeam: null,
    firstTime: [],
    secondTeam: null,
    secondTime: [],
    thirdTeam: null,
    thirdTime: [],
    applyDate: null,
    
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptName: null,
    type: null,
  },
  rules: {
    deptId: [{ required: true, message: "排班组织不能为空", trigger: "change" }],
    responsibleBy: [{ required: true, message: "排班责任人不能为空", trigger: "change" }],
    type: [{ required: true, message: "排班类型不能为空", trigger: "change" }],
    firstTeam: [{ required: true, message: "早班人员不能为空", trigger: "change" }],
    applyDate: [{ required: true, message: "适用日期范围不能为空", trigger: "change" }],
  },
})

const { queryParams, form, rules } = toRefs(data)


const editDialog = reactive({
  title: "编辑排班",
  open: false,
  form: {
    deptId: null,
    responsibleBy: null,
    type: null,
    isNoonBreak: '0',
  },
  calendarDate: new Date(),
  rules: {
    deptId: [{ required: true, message: "排班组织不能为空", trigger: "change" }],
    responsibleBy: [{ required: true, message: "排班责任人不能为空", trigger: "change" }],
    type: [{ required: true, message: "排班类型不能为空", trigger: "change" }],
  },
})

const deptOptions = ref([])
const userOptions = ref([])

// 获取下拉数据
useUserStore().getInfo().then((res)=>{
  // 获取责任人
  deptSonUserTree({deptId:res.user.dept.deptId}).then((response) => {
    if(response.code == 200) {
      deptOptions.value = [response.data]
      userOptions.value = [transformDeptTree(response.data,true)]
      userInfo.value  = response.data.userList[0];
    }
  })
})

/** 查询【请填写功能名称】列表 */
function getList() {
  loading.value = true
  scheduleList(queryParams.value).then((response) => {
    settingList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    deptId: null,
    responsibleBy: null,
    type: null,
    isNoonBreak: '0',
    firstTime: [],
    secondTeam: null,
    secondTime: [],
    thirdTeam: null,
    thirdTime: [],
    applyDate: null,
    applyDate: null,
  }
  proxy.resetForm("settingRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.slaId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "新建排班"
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["settingRef"].validate((valid) => {
    if (valid) {
      let data = {
        deptId: form.value.deptId[form.value.deptId.length - 1],
        responsibleBy: form.value.responsibleBy,
        type: Number(form.value.type),
        isNoonBreak: Number(form.value.isNoonBreak),
        firstTeam:  form.value.firstTeam?.join(),
        secondTeam: form.value.secondTeam?.join(),
        thirdTeam: form.value.thirdTeam?.join(),
        applyStartDate: form.value.applyDate[0],
        applyEndDate: form.value.applyDate[1],
      }
      if (form.value.firstTime.length > 0) {
        data.firstStartTime = form.value.firstTime[0]
        data.firstEndTime = form.value.firstTime[1]
      }
      if (form.value.secondTime.length > 0) {
        data.secondStartTime = form.value.secondTime[0]
        data.secondEndTime = form.value.secondTime[1]
      }
      if (form.value.thirdTime.length > 0) {
        data.thirdStartTime = form.value.thirdTime[0]
        data.thirdEndTime = form.value.thirdTime[1]
      }
      addSchedule(data).then((response) => {
        proxy.$modal.msgSuccess("新增成功")
        open.value = false
        getList()
      })
    }
  })
}



/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/setting/export",
    {
      ...queryParams.value,
    },
    `setting_${new Date().getTime()}.xlsx`
  )
}

getList()



/** 修改按钮操作 */
function handleUpdate(row) {
  editDialog.form= row
  editDialog.open = true
  nextTick(() => {
    shiftCalendarRef.value.init()
  })
}

const editCancel = () => {
  editDialog.open = false
  reset()
}
const editSubmitForm = () => {
  proxy.$refs["editDialogFormRef"].validate((valid) => {
    if (valid) {
      let data ={
        ...editDialog.form,
      }
      data.deptId = editDialog.form.deptId[editDialog.form.deptId.length - 1]
      putSchedule(data).then((response) => {
        proxy.$modal.msgSuccess("修改成功")
        editDialog.open = false
        getList()
      })
    }
  })
}



function transformDeptTree(deptNode, isRoot = false) {
  // 1. 处理当前部门节点
  const transformedNode = {
    id: deptNode.deptId,
    label: deptNode.deptName,
    children: []
  };

  // 2. 合并用户到同层级children（优先处理用户）
  if (deptNode.userList?.length > 0) {
    transformedNode.children.push(
      ...deptNode.userList.map(user => {
       return {
        id: user.userId,
        name: user.userName,
        label: `${user.nickName} (${user.userName})`,
        isUser: true
      }})
    );
  }

  // 3. 递归处理子部门
  if (deptNode.children?.length > 0) {
    transformedNode.children.push(
      ...deptNode.children.map(child => transformDeptTree(child))
    );
  }

  // 4. 根节点特殊处理：将第一个子元素移到最前
  if (isRoot && transformedNode.children.length > 0) {
    const firstChild = transformedNode.children.shift();
    transformedNode.children.unshift(firstChild); // 显式确保顺序
  }

  // 5. 处理空children
  if (transformedNode.children.length === 0) {
    delete transformedNode.children;
  }

  return transformedNode;
}

</script>
<style scoped lang="scss">
.searchStyle {
  display: flex;
  margin-bottom: 10px;
}
</style>
<style>
.rosteringEditDialog .h5{
  margin-top: 20px;
  font-size: 16px;
  font-weight: bold;
}
.rosteringEditDialog .h51{
  margin-top: 0;
  margin-bottom: 20px;
}
</style>

